﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Configuration;
using ResourceBlender.DAL;
using ResourceBlender.Core;

/// <summary>
/// Allows a user to select a database mode and enter credentials.
/// </summary>
public partial class DatabaseSelector : System.Web.UI.UserControl
{
    /// <summary>
    /// Gets or sets the database mode.
    /// </summary>
    /// <value>The database mode.</value>
    public DatabaseType Mode {
        get {
            if(radDBMode.SelectedIndex >= 0) {
                return (DatabaseType)Enum.Parse(typeof(DatabaseType), radDBMode.SelectedValue);
            } else {
                return DatabaseType.MySQL;
            }
        }
        set {
            radDBMode.SelectedIndex = (int)value;
        }
    }

    /// <summary>
    /// Gets or sets the host (address of the database server).
    /// </summary>
    /// <value>The host (address of the database server).</value>
    public string Host {
        get {
            return txtDBHost.Text;
        }
        set {
            txtDBHost.Text = value;
        }
    }

    /// <summary>
    /// Gets or sets the port number.
    /// </summary>
    /// <value>The port number.</value>
    public int Port {
        get {
            int port = -1;
            int.TryParse(txtDBPort.Text, out port);
            return port;
        }
        set {
            txtDBPort.Text = value.ToString();
        }
    }

    /// <summary>
    /// Gets or sets the username.
    /// </summary>
    /// <value>The username.</value>
    public string User {
        get {
            return txtDBUser.Text;
        }
        set {
            txtDBUser.Text = value;
        }
    }


    /// <summary>
    /// Gets or sets the password.
    /// </summary>
    /// <value>The password.</value>
    public string Password {
        get {
            return txtDBPassword.Text;
        }
        set {
            txtDBPassword.Text = value;
        }
    }

    /// <summary>
    /// Gets or sets the database name.
    /// </summary>
    /// <value>The database name.</value>
    public string DatabaseName {
        get {
            return txtDBDatabase.Text;
        }
        set {
            txtDBDatabase.Text = value;
        }
    }

    /// <summary>
    /// Gets or sets the table prefix.
    /// </summary>
    /// <value>The table prefix.</value>
    public string TablePrefix {
        get {
            return txtTablePrefix.Text;
        }
        set {
            txtTablePrefix.Text = value;
        }
    }

    /// <summary>
    /// Gets or sets the connection string.
    /// </summary>
    /// <value>The connection string.</value>
    public string ConnectionString {
        get {
            return txtConnectionString.Text;
        }
        set {
            txtConnectionString.Text = value;
        }
    }

    /// <summary>
    /// Returns the details entered as a connection string. If the user enters a connectionstring manually,
    /// this is always returned first, a connection string is not created unless the "Connection String"
    /// field is empty.
    /// </summary>
    /// <returns>A connection string representing the details the user entered.</returns>
    public string GetConnectionString() {
        if(string.IsNullOrEmpty(txtConnectionString.Text)) {
            return Database.GetConnectionString(Mode, Host, Port, User, Password, DatabaseName);
        } else {
            return txtConnectionString.Text;
        }
    }

    /// <summary>
    /// Attempts to fill text box values from the current settings on first load.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void Page_Load(object sender, EventArgs e)
    {
        if(!Page.IsPostBack) {
            radDBMode.DataSource = EnumBinder.EnumHelper.ToExtendedList<int>(typeof(DatabaseType));
            radDBMode.DataTextField = "Value";
            radDBMode.DataValueField = "NumericKey";
            radDBMode.DataBind();
            radDBMode.Items[2].Enabled = false;

            if(WebConfigurationManager.AppSettings.Count > 0) {
                try {
                    string selectedMode = WebConfigurationManager.AppSettings["dbtype"];
                    if(selectedMode.Length > 0) {
                        radDBMode.SelectedValue = selectedMode;
                    } else {
                        radDBMode.SelectedIndex = 0;
                    }
                    txtDBHost.Text = WebConfigurationManager.AppSettings["dbhost"];
                    txtDBPort.Text = WebConfigurationManager.AppSettings["dbport"];
                    txtDBUser.Text = WebConfigurationManager.AppSettings["dbuser"];
                    txtDBPassword.Text = WebConfigurationManager.AppSettings["dbpass"];
                    txtDBDatabase.Text = WebConfigurationManager.AppSettings["dbdatabase"];
                    txtTablePrefix.Text = WebConfigurationManager.AppSettings["tableprefix"];
                    txtConnectionString.Text = WebConfigurationManager.ConnectionStrings[0].ConnectionString;
                } catch { }
            } else {
                radDBMode.SelectedIndex = 0;
            }
            switch(radDBMode.SelectedIndex) {
                case 0:
                    txtDBPort.Text = "3306";
                    break;
                case 1:
                    txtDBPort.Text = "1433";
                    break;
            }
        }
    }

    /// <summary>
    /// Checks whether input is valid and displays error messages.
    /// </summary>
    /// <returns></returns>
    public bool ValidateInput() {
        bool valid = true;
        if(string.IsNullOrEmpty(txtConnectionString.Text)) {
            lblErrDBHost.Visible = string.IsNullOrEmpty(txtDBHost.Text);
            lblErrDBPort.Visible = string.IsNullOrEmpty(txtDBPort.Text);
            lblErrDBUser.Visible = string.IsNullOrEmpty(txtDBUser.Text);
            lblErrDBDatabase.Visible = string.IsNullOrEmpty(txtDBDatabase.Text);
            if(lblErrDBHost.Visible ||
               lblErrDBPort.Visible ||
               lblErrDBUser.Visible ||
               lblErrDBDatabase.Visible) {
                valid = false;
            }
        }
        return valid;
    }

    /// <summary>
    /// Sets the default port when the SQL server type changes.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void radDBMode_SelectedIndexChanged(object sender, EventArgs e) {
        switch(radDBMode.SelectedValue) {
            case "0":
                txtDBPort.Text = "3306";
                break;
            case "1":
                txtDBPort.Text = "1433";
                break;
        }
    }
}
